; This function just returns the address of the UDG of the given str.
; If the str is EMPTY or not a letter, 0 is returned and ERR_NR set
; to "A: Invalid Argument"
; On entry HL points to the string
; and A register is non-zero if the string must be freed (TMP string)
;
#include once <error.asm>
#include once <const.asm>
#include once <free.asm>
;
USR_STR:
ldx z80_ap           ;- ex af, af'     ; Saves A flag
sta z80_ap
txa
lda z80_h            ;- ld a,h
sta z80_a
ora z80_l            ;- or l
jeq USR_ERROR        ;- jr z,USR_ERROR ; a$ = NULL => Invalid Arg
lda z80_h            ;- ld d,h         ; Saves HL in DE, for
sta z80_d
lda z80_l            ;- ld e,l         ; later usage
sta z80_e
ldy #$00             ;- ld c,(hl)
lda (z80_hl),y
sta z80_c
inc z80_l            ;- inc hl
bne *+4
inc z80_h
ldy #$00             ;- ld a,(hl)
lda (z80_hl),y
sta z80_a
ora z80_c            ;- or c
jeq USR_ERROR        ;- jr z,USR_ERROR ; a$ = "" => Invalid Arg
inc z80_l            ;- inc hl
bne *+4
inc z80_h
ldy #$00             ;- ld a,(hl) ; Only the 1st char is needed
lda (z80_hl),y
sta z80_a
and #%11011111       ;- and 11011111b ; Convert it to UPPER CASE
                     ;- sub 'A'
lda z80_a            ;- ld l,a
sta z80_l
lda #0               ;- ld h,0
sta z80_h
asl z80_l            ;- add hl,hl
rol z80_h
asl z80_l            ;- add hl,hl
rol z80_h
asl z80_l            ;- add hl,hl	 ; hl = A * 8
rol z80_h
lda UDG              ;- ld bc,(UDG)
sta z80_c
lda UDG+1
sta z80_b
lda z80_l            ;- add hl,bc
clc
adc z80_c
sta z80_l
lda z80_h
adc z80_b
sta z80_h

;; Now checks if the string must be released
ldx z80_ap           ;- ex af,af'  ; Recovers A flag
sta z80_ap
txa
ora z80_a            ;- or a
bne *+3              ;- ret z   ; return if not
rts
lda z80_l            ;- push hl ; saves result since __MEM_FREE changes HL
pha
lda z80_h
pha
lda z80_e            ;- ex de,hl   ; Recovers original HL value
ldx z80_l
stx z80_e
sta z80_l
lda z80_d
ldx z80_h
stx z80_d
sta z80_h
jsr __MEM_FREE       ;- call __MEM_FREE
pla                  ;- pop hl
sta z80_h
pla
sta z80_l
rts                  ;- ret

USR_ERROR:
lda z80_e            ;- ex de,hl   ; Recovers original HL value
ldx z80_l
stx z80_e
sta z80_l
lda z80_d
ldx z80_h
stx z80_d
sta z80_h
ldx z80_ap           ;- ex af,af'  ; Recovers A flag
sta z80_ap
txa
ora z80_a            ;- or a
beq *+5              ;- call nz,__MEM_FREE
jsr __MEM_FREE
                     ;- ld a,ERROR_InvalidArg
                     ;- ld (ERR_NR), a
lda #<0              ;- ld hl,0
sta z80_l
lda #>0
sta z80_h
rts                  ;- ret


